<?php

namespace app\model;

use think\Model;

class Merchant extends Model
{
    public function addOrUpdate(): array
    {
        $param = request()->post();
        $this->exists(!empty($param['id']))->save($param);
        return $this->toArray();
    }

    public function lst(): array
    {
        $param = request()->param();
        $data = $this->order(['create_time' => 'desc'])->paginate([
            "list_rows" => $param['size'] ?? 30,
            "page" => $param['page'] ?? 1
        ])->toArray();
        return pageData($data);
    }

    public function balanceUpdate(): array
    {
        $param = request()->post();
        $data = $this->find($param['mer_id']);
        if (empty($data)) throw new \Exception("商户不存在", 7001);
        $this->startTrans();
        if ($param['type'] == 1) {
            $new_money = $data->balance + $param['money'];
            $data->inc("balance", $param['money']);
        } else {
            $new_money = $data->balance - $param['money'];
            $data->dec("balance", $param['money']);
        }
        $data->save();
        app(MerchantBalance::class)->save([
            "mer_id" => $param['mer_id'],
            "order_sn" => setOrderSn("MR"),
            "content" => $param['content'],
            "money" => $param['money'],
            "old_money" => $param['old_money'],
            "new_money" => $new_money,
            "type" => $param['type'],
            "des" => $param['des']
        ]);
        $this->commit();
        return $this->toArray();
    }

    public function updateState(): array
    {
        $param = request()->param();
        $data = $this->where("id", $param['id'])->find();
        if (empty($data)) throw new \Exception("商户不存在", 7001);
        $data->state = $data['state'] == 1 ? 2 : 1;
        $data->save();
        return $data->toArray();
    }
}
